package com.my.xinyidaixi.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.my.xinyidaixi.Fragment.Home_Fragment;
import com.my.xinyidaixi.Fragment.Mine_Fragment;
import com.my.xinyidaixi.Fragment.Order_Fragment;
import com.my.xinyidaixi.R;
import com.my.xinyidaixi.Util.UpdateService;
import com.wevey.selector.dialog.NormalAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends Activity implements View.OnClickListener {

    private LinearLayout view_1,view_2,view_3;
    private FragmentManager fragmentManager;
    private Home_Fragment homefragment;
    private Order_Fragment orderfragment;
    private Mine_Fragment minefragment;
    private boolean mIsExit;
    private ImageView img_1;
    private ImageView img_2;
    private ImageView img_3;
    private TextView text_1;
    private TextView text_2;
    private TextView text_3;
    private static int REQUESTPERMISSION = 110 ;
    private Intent service;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getFragmentManager();
        initView();
        setTabSelection(0);
        img_1.setImageResource(R.mipmap.home_icon_select);
        text_1.setTextColor(getResources().getColor(R.color.cyan));
        update();
    }

    public void initView()
    {
        //获取三个下栏三个按钮
        view_1 = (LinearLayout) findViewById(R.id.view_1);
        img_1 = (ImageView) findViewById(R.id.activity_img_1);
        img_2 = (ImageView) findViewById(R.id.activity_img_2);
        img_3 = (ImageView) findViewById(R.id.activity_img_3);
        text_1 = (TextView) findViewById(R.id.activity_text_1);
        text_2 = (TextView) findViewById(R.id.activity_text_2);
        text_3 = (TextView) findViewById(R.id.activity_text_3);


        view_2 = (LinearLayout) findViewById(R.id.view_2);
        view_3 = (LinearLayout) findViewById(R.id.view_3);

        view_1.setOnClickListener(this);
        view_2.setOnClickListener(this);
        view_3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.view_1 :
                setTabSelection(0);
                clearselection();
                img_1.setImageResource(R.mipmap.home_icon_select);
                text_1.setTextColor(getResources().getColor(R.color.cyan));
                break;
            case R.id.view_2:
                setTabSelection(1);
                clearselection();
                img_2.setImageResource(R.mipmap.order_icon_select);
                text_2.setTextColor(getResources().getColor(R.color.cyan));
                break;
            case R.id.view_3:
                setTabSelection(2);
                clearselection();
                img_3.setImageResource(R.mipmap.mine_icon_select);
                text_3.setTextColor(getResources().getColor(R.color.cyan));
                break;
            default:break;
        }
    }

    //选择标签
    public void setTabSelection(int index)
    {
        clearselection();
        FragmentTransaction transaction=fragmentManager.beginTransaction();
        hideFragment(transaction);
        switch (index)
        {
            case 0:
                if(homefragment ==null)
                {
                    homefragment =new Home_Fragment();
                    transaction.add(R.id.Content, homefragment);
                }
                else
                {
                    transaction.show(homefragment);
                }
                break;
            case 1:
                if(orderfragment==null)
                {
                    orderfragment=new Order_Fragment();
                    transaction.add(R.id.Content,orderfragment);
                }
                else
                {
                    transaction.show(orderfragment);
                }
                break;
            case 2:
                if(minefragment==null)
                {
                    minefragment=new Mine_Fragment();
                    transaction.add(R.id.Content,minefragment);
                }
                else
                {
                    transaction.show(minefragment);
                }
                break;
        }
        transaction.commit();
    }

    //清除选择
    public void clearselection()
    {
        img_1.setImageResource(R.mipmap.home_icon_noselect);
        img_2.setImageResource(R.mipmap.order_icon_noselect);
        img_3.setImageResource(R.mipmap.mine_icon_noselect);
        text_1.setTextColor(getResources().getColor(R.color.new_black));
        text_2.setTextColor(getResources().getColor(R.color.new_black));
        text_3.setTextColor(getResources().getColor(R.color.new_black));
    }

    //隐藏fragment
    public void hideFragment(FragmentTransaction transaction)
    {
        if(homefragment !=null)
        {

            transaction.hide(homefragment);
        }

        if(orderfragment!=null)
        {
            transaction.hide(orderfragment);
        }

        if(minefragment!=null)
        {
            transaction.hide(minefragment);
        }
    }

    //退出程序按钮
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if (mIsExit)
            {
                this.finish();
            }
            else
            {
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                mIsExit = true;
                new Handler().postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mIsExit = false;
                    }
                }, 2000);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    //再打开应用，并不会再看到启动页
    @Override
    public void onBackPressed() {
        // super.onBackPressed();   不要调用父类的方法
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }
    //实现自动更新
    public void update()
    {
        String url="http://wx.mindaxiaosi.com/xinyidaixi/version_info";
        OkHttpClient okHttpClient=new OkHttpClient();
        Request request=new Request.Builder()
                .url(url)
                .build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e)
            {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String string=response.body().string();
                            JSONObject object=new JSONObject(string);
                            if(getVersionCode(MainActivity.this).equals(object.getString("version")))
                            {
                                //Toast.makeText(MainActivity.this,"versioncode相同",Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                update_Dialog();

                            }
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        } catch (JSONException e)
                        {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUESTPERMISSION) {
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (service != null)
                        startService(service);
                }

                else
                {
                    Toast.makeText(this,"没有权限安装不了",Toast.LENGTH_SHORT).show();
//提示没有权限，安装不了咯
                }
            }
        }
    }

    //获取当前versioncode
    public String getVersionCode(Context context){
        PackageManager packageManager=context.getPackageManager();
        PackageInfo packageInfo;
        String versionCode="";
        try {
            packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
            versionCode=packageInfo.versionCode+"";
        } catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return versionCode;
    }

    private void update_Dialog() {

        new NormalAlertDialog.Builder(this).setTitleVisible(false)
                .setContentText("发现新版本啦！要更新吗？")
                .setContentTextColor(R.color.cyan)
                .setLeftButtonText("更新")
                .setLeftButtonTextColor(R.color.black)
                .setRightButtonText("取消")
                .setRightButtonTextColor(R.color.black)
                .setOnclickListener(new com.wevey.selector.dialog.DialogInterface.OnLeftAndRightClickListener<NormalAlertDialog>() {
                    @Override
                    public void clickLeftButton(NormalAlertDialog dialog, View view) {
                                //启动服务
                                service = new Intent(MainActivity.this,UpdateService.class);
                                if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                                {
                                    //申请权限
                                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTPERMISSION);
                                    Toast.makeText(MainActivity.this,"请允许权限进行下载安装",Toast.LENGTH_SHORT).show();
                                }
                                else
                                {
                                    startService(service);
                                }

                       // ToastUtil.shortToast(MainActivity.this,"更新");
                        dialog.dismiss();//对话框消失
                    }

                    @Override
                    public void clickRightButton(NormalAlertDialog dialog, View view) {

                        dialog.dismiss();
                    }
                })
                .build()
                .show();
    }

    //实现自动更新
}
